package com.ck.ips.service.impl.sys;

import com.ck.common.model.OperationResult;
import com.ck.common.model.User;
import com.ck.common.page.PageInfo;
import com.ck.core.constant.PageConstant;
import com.ck.core.constant.UserType;
import com.ck.core.context.UserContextHolder;
import com.ck.ips.core.listener.event.LoginSuccessEvent;
import com.ck.ips.dao.sys.UserMapper;
import com.ck.ips.model.vo.sys.UserListVO;
import com.ck.ips.service.sys.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @Description: 系统用户service impl
* @Author: hf
* @Date:    2019/4/29 9:53
* @Version: 1.0
*/
@Service("userService")
public class UserServiceImpl implements UserService {
	/** 密码最小位数 */
	private final int MIN_PWD_LENGTH = 6;
	/** 密码最大位数 */
	private final int MAX_PWD_LENGTH = 20;
	/** 用户名最大长度 */
	private final int MAX_USER_NAME_LENGTH = 16;
	@Autowired
	private UserMapper userMapper;

	@Override
	public User getUserByUserName(String userName){
		return userMapper.getUserByUserName(userName);
	}

	@Override
	public User getUserById(Long userId) {
		return userMapper.getUserById(userId);
	}

	/**
	 * 保存用户
	 *
	 * @param user    User
	 * @param roleIds 角色IDS
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult insertUser(User user, UserType userType, String roleIds) {
		if ( StringUtils.isBlank(user.getUserName()) ) {
			return OperationResult.newValidateFailOperationResult("用户名不能为空");
		}
		if ( user.getUserName().length() > MAX_USER_NAME_LENGTH) {
			return OperationResult.newValidateFailOperationResult("用户名称不能超过"+ MAX_USER_NAME_LENGTH +"位");
		}
		if ( userType == null ) {
			return OperationResult.newValidateFailOperationResult("输入添加用户的账户类型");
		}
		//验证用户名
		User oldUser = this.getUserByUserName(user.getUserName());
		if (oldUser != null) {
			return OperationResult.newValidateFailOperationResult("用户名已存在");
		}
		user.setType(userType.name());
		user.setAddTime(System.currentTimeMillis());
		user.setOperator(UserContextHolder.currentUser().getUserName());
		user.setStatus(Boolean.TRUE);
		//保存用户
		userMapper.insertUser(user);
		Long userId = user.getUserId();
		if ( userId != null && StringUtils.isNotBlank(roleIds) ) {
			userMapper.insertUserRole(userId, roleIds.split(","));
		}
		return OperationResult.newSuccessTipsOperationResult("添加用户：" + user.getUserName());
	}

	/**
	 * 修改用户
	 *
	 * @param user    User
	 * @param roleIds 角色IDS
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult updateUser(User user, String roleIds) {
		if ( user == null || user.getUserId() == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要修改的用户");
		}
		User existedUser = this.getUserById(user.getUserId());
		if ( existedUser == null ) {
			return OperationResult.newValidateFailOperationResult("该用户不存在");
		}
		// 不能修改用户名
		user.setUserName(null);
		// 不能修改用户类型
		user.setType(null);
		user.setUpdateTime(System.currentTimeMillis());
		user.setOperator(UserContextHolder.currentUser().getUserName());
		//更新用户
		userMapper.updateUserById(user);

		Long userId = user.getUserId();
		if ( roleIds != null ) {
			//删除用户角色关系
			userMapper.deleteUserRoleByUserId(userId);
			//保存用户角色关系
			if ( !StringUtils.isBlank(roleIds) ) {
				userMapper.insertUserRole(userId, roleIds.split(","));
			}
		}
		return  OperationResult.newSuccessTipsOperationResult("修改用户：" + existedUser.getUserName());
	}


	/**
	 * 获取用戶列表
	 *
	 * @param status      状态
	 * @param userName    用户名
	 * @param pageNum     当前页
	 * @param pageSize    条数
	 * @return PageInfo<UserListVO>
	 */
	@Override
	public PageInfo<UserListVO> listUser(Integer status, String userName,String realName,String mobile, Long departmentId,String roleName,Integer pageNum, Integer pageSize){
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<UserListVO> page = userMapper.listUser(status, userName,realName,mobile,departmentId,roleName);
		return PageInfo.convert(page);
	}

	/**
	 * 根据主键更新
	 * @param user
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult updateByPrimaryKey(User user) {
		user.setUpdateTime(System.currentTimeMillis());
		userMapper.updateUserById(user);
		return OperationResult.newSuccessTipsOperationResult("更新用户信息：" +  user.getUserName());
	}

	/**
	 * 重置密码
	 * @param userId 用户ID
	 * @param password 密码
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult resetPassword(Long userId, String password){
		if (userId == null) {
			return OperationResult.newValidateFailOperationResult("请选择要操作的用户");
		}
		if (StringUtils.isBlank(password)) {
			return OperationResult.newValidateFailOperationResult("请输入重置的密码");
		}
		/*if ( password.length() < MIN_PWD_LENGTH ) {
			return OperationResult.newValidateFailOperationResult("密码位数不能低于6位");
		}
		if ( password.length() > MAX_PWD_LENGTH ) {
			return OperationResult.newValidateFailOperationResult("密码位数不能大于20位");
		}
		if ( !com.ck.core.util.StringUtils.isLetterDigit(password) ) {
			return OperationResult.newValidateFailOperationResult("密码仅能为6~20位字母+数字组合");
		}*/
		//查询用户
		User optUser = this.getUserById(userId);
		if (optUser == null) {
			return OperationResult.newValidateFailOperationResult("被重置密码的用户不存在");
		}
		optUser.setPassword(password);
		optUser.setUpdateTime(System.currentTimeMillis());
		userMapper.updateUserById(optUser);

		return OperationResult.newSuccessTipsOperationResult("重置密码：" + optUser.getUserName());
	}

	/**
	 * 启用禁用用户
	 *
	 * @param userId      待操作的用户
	 * @param status      启用/停用
	 * @author linqiang
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult enableDisableUser(Long userId, Boolean status) {
		if ( userId == null) {
			return OperationResult.newValidateFailOperationResult("请选择要操作的用户");
		}
		User optUser = this.getUserById(userId);
		if( null == optUser ){
			return OperationResult.newValidateFailOperationResult("用户已被删除或不存在");
		}
		if( UserType.SUPER.name().equals(optUser.getType()) ){
			return OperationResult.newValidateFailOperationResult("超级管理员不允许禁用");
		}
		optUser.setStatus(status);
		optUser.setUpdateTime(System.currentTimeMillis());
		userMapper.updateUserById(optUser);
		return OperationResult.newSuccessTipsOperationResult("启用/禁用账户：" + optUser.getUserName());
	}

	@Override
	public OperationResult saveLoginSuccessRecord(LoginSuccessEvent loginSuccessEvent) {
		userMapper.saveLoginSuccessRecord(loginSuccessEvent);

		User loginUser = userMapper.getUserByUserName(loginSuccessEvent.getUserName());
		loginUser.setLastLoginIp(loginSuccessEvent.getIp());
		loginUser.setLastLoginTime(loginSuccessEvent.getTimestamp());
		loginUser.setUpdateTime(loginSuccessEvent.getTimestamp());
		userMapper.updateUserById(loginUser);

		return OperationResult.newSuccessOperationResult();
	}

	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult deleteUser(Long userId) {
		if ( userId == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要删除的用户数据");
		}
		User oldUser = userMapper.getUserById(userId);
		if ( oldUser == null ) {
			return OperationResult.newValidateFailOperationResult("要删除的用户数据不存在");
		}
		userMapper.deleteUserRoleByUserId(userId);
		userMapper.deleteUser(userId);
		return OperationResult.newSuccessTipsOperationResult("删除用户："+oldUser.getUserName());
	}

    @Override
    public List<Long> getRoleByUserId(Long userId) {
        return userMapper.getRoleByUserId(userId);
    }

}
